import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:window_manager/window_manager.dart';
import 'package:win32/win32.dart';
import 'dart:ffi'; // 用于调用 Windows 原生 API
import 'dart:ui' as ui; // 为 dart:ui 加上前缀
import 'package:ffi/ffi.dart'; // 导入 ffi 库

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await windowManager.ensureInitialized();

  // 初始化窗口设置
  WindowOptions windowOptions = const WindowOptions(
    size: ui.Size(400, 520), // 使用带前缀的 Size
    center: true,
    skipTaskbar: false,
    alwaysOnTop: false,
  );

  windowManager.waitUntilReadyToShow(windowOptions, () async {
    await windowManager.show();
    await windowManager.focus();
  });

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Message List',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: MessageListPage(),
    );
  }
}

class MessageListPage extends StatefulWidget {
  @override
  _MessageListPageState createState() => _MessageListPageState();
}

class _MessageListPageState extends State<MessageListPage> with WindowListener {
  final List<Message> messages = List.generate(
    20,
    (index) => Message(
      title: '消息标题 #$index',
      content: '这是消息内容的简短描述...',
      time: '10:${index.toString().padLeft(2, '0')} AM',
      icon: Icons.message_rounded,
    ),
  );

  int _selectedIndex = 0;

  @override
  void initState() {
    super.initState();
    windowManager.addListener(this);
  }

  @override
  void onWindowFocus() {
    _moveWindowToCursor();
  }

  void _moveWindowToCursor() {
    final cursorPos = calloc<POINT>();
    GetCursorPos(cursorPos);

    windowManager.setBounds(Rect.fromLTWH(
      cursorPos.ref.x.toDouble(),
      cursorPos.ref.y.toDouble(),
      400,
      300,
    ));

    free(cursorPos);
  }

  void _handleKey(RawKeyEvent event) {
    if (event is RawKeyDownEvent) {
      if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
        setState(() {
          _selectedIndex = (_selectedIndex - 1) % messages.length;
        });
      } else if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
        setState(() {
          _selectedIndex = (_selectedIndex + 1) % messages.length;
        });
      } else if (event.logicalKey == LogicalKeyboardKey.enter) {
        Clipboard.setData(ClipboardData(text: messages[_selectedIndex].title));
        // windowManager.hide();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return RawKeyboardListener(
      focusNode: FocusNode()..requestFocus(),
      onKey: _handleKey,
      child: Scaffold(
        appBar: AppBar(title: Text('消息列表')),
        body: ListView.builder(
          itemCount: messages.length,
          itemBuilder: (context, index) {
            final message = messages[index];
            return ListTile(
              leading: CircleAvatar(
                child: Icon(message.icon, color: Colors.white),
                backgroundColor: Colors.blueAccent,
              ),
              title: Text(
                message.title,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: _selectedIndex == index ? Colors.blue : Colors.black,
                ),
              ),
              subtitle: Text(message.content),
              trailing: Text(
                message.time,
                style: TextStyle(color: Colors.grey),
              ),
            );
          },
        ),
      ),
    );
  }
}

class Message {
  final String title;
  final String content;
  final String time;
  final IconData icon;

  Message({
    required this.title,
    required this.content,
    required this.time,
    required this.icon,
  });
}
